<!-- ChatBody.vue -->
<template>
    <div class="chat-wrapper">
        <!-- 上部分可滚动区域 -->

        <div class="chat-body">

            <!-- 单个下拉框 -->
            <div v-if="analysis" class="dropdown-panel">
                <div class="dropdown-header" @click="toggleDropdown">
                    <span>{{ analysis.name }}分析详情：</span>
                    <el-icon :class="{ 'is-rotate': isExpanded }">
                        <ArrowDown />
                    </el-icon>
                </div>
                <div class="dropdown-content" v-show="isExpanded">
                    <div class="analysis-section">
                        <h4>详细分析</h4>
                        <p>{{ analysis.analysis.detailed_analysis }}</p>
                    </div>
                    <div class="analysis-section">
                        <h4>游览建议</h4>
                        <p>{{ analysis.analysis.visiting_tips }}</p>
                    </div>
                    <div class="analysis-section">
                        <h4>预算估算</h4>
                        <p>{{ analysis.analysis.budget_estimation }}</p>
                    </div>
                    <div class="analysis-section">
                        <h4>推荐时长</h4>
                        <p>{{ analysis.analysis.recommended_duration }}</p>
                    </div>
                </div>
            </div>


            <MessageList :messages="messages" />


        </div>

        <!-- 下部分固定区域 -->
        <div class="input-area">
            <el-input v-model="inputMessage" placeholder="请输入消息..." :rows="2" type="textarea" resize="none"
                @keyup.enter.ctrl="handleSend" />
            <el-button type="primary" class="send-button" @click="handleSend">
                发送
            </el-button>
        </div>
    </div>

</template>

<script setup lang="ts">

const AI_AVATAR = '/AICHAT.png'
const USER_AVATAR = '/user-avatar.png'

import { ArrowDown } from '@element-plus/icons-vue'
import { nextTick, ref, watch, computed } from 'vue'
import MessageList from './MessageList.vue'
import { continuousChat } from '@/api/Gpt'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores/UserStore'
// 添加输入框相关的响应式变量
const inputMessage = ref('')

const userStore = useUserStore()
const userAvatar = computed(() => userStore.userInfo.avatarUrl || USER_AVATAR)

// 修改消息接口
interface Message {
    role: 'user' | 'assistant'  // 改为 role 字段
    content: string
    avatar?: string  // 可选的头像字段
}




// 内部维护消息列表
const messages = ref<Message[]>([
    {
        role: 'assistant',
        content: '你好，我是Journeo助手，有什么可以帮你的吗？',
        avatar: AI_AVATAR
    }
])

interface Analysis {
    name: string
    spotId: number
    analysis: {
        detailed_analysis: string
        visiting_tips: string
        budget_estimation: string
        recommended_duration: string
    }
}


// 添加滚动到底部的方法
const scrollToBottom = () => {
    nextTick(() => {
        const chatBody = document.querySelector('.chat-body')
        if (chatBody) {
            chatBody.scrollTop = chatBody.scrollHeight
        }
    })
}



// 定义响应接口
interface ApiResponse {
    status: string
    message: string
    data: {
        response: string
    }
}

// 修改 handleSend 函数
const handleSend = async () => {
    if (!inputMessage.value.trim()) return

    const userMessage: Message = {
        role: 'user',
        content: inputMessage.value,
        avatar: userAvatar.value
    }
    
    messages.value.push(userMessage)
    scrollToBottom()

    const requestData = {
        newMessage: inputMessage.value,
        chatHistory: convertMessagesToHistory(messages.value)
    }

    try {
        inputMessage.value = ''
        const response = await continuousChat(requestData)
        
        if (response?.data) {
            const apiResponse = response as unknown as ApiResponse
            if (apiResponse.status === 'success') {
                const aiMessage: Message = {
                    role: 'assistant',
                    content: apiResponse.data.response,
                    avatar: AI_AVATAR
                }
                messages.value.push(aiMessage)
                scrollToBottom()
            }
        }
    } catch (error) {
        console.error('发送消息失败:', error)
        ElMessage.error('发送消息失败')
    }
}
// 修复 convertMessagesToHistory 函数
const convertMessagesToHistory = (messages: Message[]) => {
    return messages.map(msg => ({
        role: msg.role,
        content: msg.content,
        avatar: msg.avatar, // 保留头像信息
    }))
};


const isExpanded = ref(true)

const toggleDropdown = () => {
    isExpanded.value = !isExpanded.value
}


// 添加转换函数
const convertAnalysisToMessage = (analysis: Analysis): Message => {
    return {
        role: 'assistant',
        content: `
你好，我是JOURNEO助手，这是关于景点
${analysis.name}的分析报告：

详细分析：
${analysis.analysis.detailed_analysis}

游览建议：
${analysis.analysis.visiting_tips}

预算估算：
${analysis.analysis.budget_estimation}

推荐时长：
${analysis.analysis.recommended_duration}
    `,
        avatar: AI_AVATAR
    }
}


const props = defineProps<{
    analysis?: Analysis
}>()

// 监听analysis变化
watch(() => props.analysis, (newAnalysis) => {
    if (newAnalysis) {

        // 清空现有消息
        messages.value = []
        // 添加分析消息
        messages.value.push(convertAnalysisToMessage(newAnalysis))
        scrollToBottom() // 分析消息加载后滚动
    }
}, { immediate: true })
</script>

<style scoped>
.chat-wrapper {
    height: 100%;
    /* 设置固定高度 */
    display: flex;
    flex-direction: column;
    border: 1px solid #eee;
    /* 添加边框便于视觉识别 */
    border-radius: 8px;
    background: white;
    overflow: hidden;
    /* 防止内容溢出 */
}

.chat-body {
    flex: 1;
    overflow-y: auto;
    padding: 16px;
    height: calc(100vh - 220px); 
    border-radius: 0%;
}

/* 下拉框样式 */
.dropdown-panel {
    background: white;
    border-radius: 8px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
    margin-bottom: 16px;
    position: sticky;
    top: 0;
    z-index: 10;
    width: 100%;
    /* 使用全宽 */
    max-width: 600px;
    /* 设置最大宽度 */
    margin-left: auto;
    margin-right: auto;
}

.dropdown-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 12px 16px;
    cursor: pointer;
    user-select: none;
    color: #333;
}

.dropdown-content {
    padding: 16px;
    border-top: 1px solid #eee;
}

/* 添加分析部分样式 */
.analysis-section {
    margin-bottom: 16px;
}

.analysis-section:last-child {
    margin-bottom: 0;
}

.analysis-section h4 {
    color: #409EFF;
    margin: 0 0 6px;
    /* 稍微减小边距 */
    font-size: 13px;
    /* 减小标题字体 */
}

.analysis-section p {
    margin: 0;
    line-height: 1.6;
    color: #666;
    font-size: 13px;
    /* 减小正文字体 */
}

.is-rotate {
    transform: rotate(180deg);
    transition: transform 0.3s;
}

.messages-container {
    display: flex;
    flex-direction: column;
    gap: 16px;
}

/* 消息样式调整 */
.message {
    display: flex;
    gap: 12px;
    max-width: 80%;
    margin-bottom: 16px;
}

.message.user {
    margin-left: auto;
    flex-direction: row-reverse;
}

.message.assistant {
    margin-right: auto;
}


.message-content {
    padding: 12px;
    border-radius: 8px;
    background: #f5f7fa;
    word-break: break-word;
}



.message.user .message-content {
    background: #409EFF;
    color: white;
    border-radius: 8px 8px 0 8px;
}

.message.assistant .message-content {
    background: #f4f6f8;
    color: #333;
    border-radius: 8px 8px 8px 0;
}

.message-avatar {
    flex-shrink: 0;
}

.input-area {
    height: 100px;
    padding: 16px;
    border-top: 1px solid #eee;
    background: white;
    display: flex;
    gap: 12px;
    box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);
}

.input-area :deep(.el-textarea__inner) {
    resize: none;
    height: 68px !important;
}

.send-button {
    align-self: flex-end;
}
</style>